package com.qijian.web.controller.system;

import cn.hutool.core.collection.CollectionUtil;
import com.qijian.common.annotation.Anonymous;
import com.qijian.common.annotation.Log;
import com.qijian.common.core.controller.BaseController;
import com.qijian.common.core.domain.AjaxResult;
import com.qijian.common.core.domain.entity.SysDictData;
import com.qijian.common.core.page.TableDataInfo;
import com.qijian.common.core.redis.RedisCache;
import com.qijian.common.enums.BusinessType;
import com.qijian.common.exception.ServiceException;
import com.qijian.common.utils.StringUtils;
import com.qijian.common.utils.poi.ExcelUtil;
import com.qijian.system.service.ISysDictDataService;
import com.qijian.system.service.ISysDictTypeService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 数据字典信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dict/data")
public class SysDictDataController extends BaseController {
    private ISysDictDataService dictDataService;

    private ISysDictTypeService dictTypeService;

    private RedisCache redisCache;

    @Autowired
    public void setDictDataService(ISysDictDataService dictDataService) {
        this.dictDataService = dictDataService;
    }

    @Autowired
    public void setDictTypeService(ISysDictTypeService dictTypeService) {
        this.dictTypeService = dictTypeService;
    }

    @Autowired
    public void setRedisCache(RedisCache redisCache) {
        this.redisCache = redisCache;
    }

    @GetMapping("/list")
    public TableDataInfo list(SysDictData dictData) {
        startPage();
        return getDataTable(dictDataService.selectDictDataList(dictData));
    }

    //    @PreAuthorize("@ss.hasPermi('system:dict:list')")
    @GetMapping("/list/all")
    public TableDataInfo all(SysDictData dictData) {
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        return getDataTable(list);
    }

    @Log(title = "字典数据", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:dict:export')")
    @GetMapping("/export")
    public AjaxResult export(SysDictData dictData) {
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        ExcelUtil<SysDictData> util = new ExcelUtil<>(SysDictData.class);
        return util.exportExcel(list, "字典数据");
    }

    /**
     * 查询字典数据详细
     */
    @GetMapping(value = "/{dictCode}")
    public AjaxResult getInfo(@PathVariable Long dictCode) {
        return AjaxResult.success(dictDataService.selectDictDataById(dictCode));
    }

    /**
     * 根据字典类型查询字典数据信息
     */
    @GetMapping(value = "/type/{dictType}")
    public AjaxResult dictType(@PathVariable String dictType) {
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (StringUtils.isNull(data)) {
            data = new ArrayList<>();
        }
        return AjaxResult.success(data);
    }


    /***
     * 匿名获取字典值(用于外部供应商访问)
     * @param dictType
     * @return
     */
    @Anonymous
    @GetMapping(value = "/typeA/{dictType}")
    public AjaxResult dictTypeForAnonymous(@PathVariable String dictType) {
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (StringUtils.isNull(data)) {
            data = new ArrayList<>();
        }
        return AjaxResult.success(data);
    }



    /**
     * 根据字典类型查询字典数据信息
     */
    @GetMapping(value = "/dictTypeChildren/{dictType}/{dictType1}")
    public AjaxResult dictTypeChildren(@PathVariable String dictType, @PathVariable String dictType1) {
        List<SysDictData> data = dictTypeService.selectDictDataByType("reason_type_factory_org");
        List<SysDictData> data1 = dictTypeService.selectDictDataByType(dictType1);
        if (StringUtils.isNull(data)) {
            data = new ArrayList<>();
        }
        if (CollectionUtils.isNotEmpty(data1)) {
            List<SysDictData> dataNew = new ArrayList<>();
            Map<String, List<SysDictData>> listMap = data1.stream().collect(Collectors.groupingBy(e -> e.getCssClass()));
            List<SysDictData> finalData = data;
            listMap.forEach((k, v) ->{
                finalData.stream().filter(e->e.getDictLabel().equals(k)).findFirst().ifPresent(m->{
                    SysDictData data2  = m;
                    data2.setChildren(v);
                    dataNew.add(data2);
                });
            });
            return  AjaxResult.success(dataNew);
        }
        return AjaxResult.success(data);
    }

    @Anonymous
    @GetMapping(value = "/typechange/{dictType}/{uuid}")
    public AjaxResult dictTypeByUuid(@PathVariable("uuid") String uuid, @PathVariable("dictType") String dictType) {
        if (CollectionUtil.isEmpty(redisCache.keys("*".concat(uuid)))) {
            throw new ServiceException("E01:无权限操作");
        }
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (StringUtils.isNull(data)) {
            data = new ArrayList<>();
        }
        return AjaxResult.success(data);
    }

    @GetMapping(value = "/type/page/{dictType}")
    public TableDataInfo dictTypePage(@PathVariable String dictType) {
        startPage();
        List<SysDictData> data = dictTypeService.selectDictDataByTypePage(dictType);
        if (StringUtils.isNull(data)) {
            data = new ArrayList<>();
        }
        return getDataTable(data);
    }

    /**
     * 新增字典类型
     */
//    @PreAuthorize("@ss.hasPermi('system:dict:add')")
    @Log(title = "字典数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDictData dict) {
        dict.setCreateBy(getUsername());
        return toAjax(dictDataService.insertDictData(dict));
    }

    /**
     * 新增字典类型
     */
    @PreAuthorize("@ss.hasPermi('system:dict:add')")
    @Log(title = "字典数据", businessType = BusinessType.INSERT)
    @PostMapping("/save")
    public void saveAll(@Validated @RequestBody List<SysDictData> dicts) {
        dictDataService.insertBatch(dicts);
    }

    /**
     * 修改保存字典类型
     */
//    @PreAuthorize("@ss.hasPermi('system:dict:edit')")
    @Log(title = "字典数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDictData dict) {
        dict.setUpdateBy(getUsername());
        return toAjax(dictDataService.updateDictData(dict));
    }

    /**
     * 删除字典类型
     */
    @PreAuthorize("@ss.hasPermi('system:dict:remove')")
    @Log(title = "字典类型", businessType = BusinessType.DELETE)
    @DeleteMapping("/{dictCodes}")
    public AjaxResult remove(@PathVariable Long[] dictCodes) {
        dictDataService.deleteDictDataByIds(dictCodes);
        return success();
    }
}
